package com.example.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.store.common.BaseContext;
import com.example.store.common.IpUtil;
import com.example.store.common.Result;
import com.example.store.entity.Cart;
import com.example.store.entity.Seller;
import com.example.store.entity.Time;
import com.example.store.service.SellerService;
import com.example.store.service.TimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

//销售相关操作
@RestController
@RequestMapping("/seller")
public class SellerController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private TimeService timeService;

//    生成日志
    private void makeTime(String id, HttpServletRequest request, String operate){
        Time time = Time.createTime(id, 4);
        String ip = IpUtil.getIp(request);
        time.setIp(ip);
        time.setOperate(operate);
        timeService.save(time);
    }

//    管理员登录，id固定为root
    @PostMapping("/adminLogin")
    public Result<String> adminLogin(@RequestBody Seller user, HttpServletRequest request){
        if(user==null||user.getId()==null||user.getPwd()==null||user.getId().equals("")||user.getPwd().equals("")){
            return Result.error("请输入id及密码");
        }
        if(!user.getId().equals("root")){
            return Result.error("错误的管理员账号");
        }

        Seller user1 = sellerService.getById(user.getId());
        if(user1 == null){
            user1 = new Seller();
            user1.setId("root");
            user1.setPwd("root");
            makeTime(user1.getId(), request, "首次创建账号");

            sellerService.save(user1);
        }
        if(!user.getPwd().equals(user1.getPwd())){
            return Result.error("密码错误");
        }

//        id存入线程中，方便获取
        BaseContext.setCurrentId(user1.getId());

//        记录日志
        Time time = Time.createTime(user1.getId(), 5);
        String ip = IpUtil.getIp(request);
        time.setIp(ip);
        request.getSession().setAttribute("ip", ip);
        timeService.save(time);
        request.getSession().setAttribute("user", user1.getId());

        return Result.success("欢迎登录");
    }

//    销售人员登录
    @PostMapping("/login")
    public Result<String> login(@RequestBody Seller user, HttpServletRequest request){
        if(user==null||user.getId()==null||user.getPwd()==null||user.getId().equals("")||user.getPwd().equals("")){
            return Result.error("请输入id及密码");
        }
        String welcome = "欢迎登陆";

//        在id前增加s，以与用户区分开
        user.setId("s"+user.getId());
        Seller user1 = sellerService.getById(user.getId());
        if(user1 == null){//新销售员
            user1 = new Seller();
            user1.setId(user.getId());
            user1.setPwd(user.getPwd());
            sellerService.save(user);
            welcome = "欢迎注册，请尽快完善个人信息";
        }
        else{
            if(!user.getPwd().equals(user1.getPwd())){
                return Result.error("密码错误");
            }
        }

        BaseContext.setCurrentId(user1.getId());

//        记录日志
        Time time = Time.createTime(user1.getId(), 2);
        String ip = IpUtil.getIp(request);
        time.setIp(ip);
        request.getSession().setAttribute("ip", ip);
        timeService.save(time);
        request.getSession().setAttribute("user", user1.getId());

        return Result.success(welcome);
    }


//    获取销售员/管理员信息
    @GetMapping("/info")
    public Result<Seller> info(){
//        用户校验
        String id = BaseContext.getCurrentId();
        if(id==null){
            return Result.error("你咋回事");
        }
        Seller user = sellerService.getById(id);
        if(user==null){
            return Result.error("你咋回事");
        }
//        隐藏地址
        user.setPwd("none");
        return Result.success(user);
    }

//    登出
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){

//        用户校验，记录日志
        String id = BaseContext.getCurrentId();
        if(id!=null){
            if(!id.equals("guest")&&!id.equals("root")){
                Time time = Time.createTime(id, 3);
                time.setIp(IpUtil.getIp(request));
                timeService.save(time);
            }
            else if(id.equals("root")){
                Time time = Time.createTime(id, 6);
                time.setIp(IpUtil.getIp(request));
                timeService.save(time);
            }

//            清空session并销毁
            request.getSession().removeAttribute("user");
            request.getSession(false).invalidate();
        }
        return Result.success("欢迎下次再来");
    }

    //销售人员修改信息或管理员修改
    @PostMapping("/update")
    public Result<Seller> update(@RequestBody Seller user, HttpServletRequest request){
//        用户校验
        String id = BaseContext.getCurrentId();
        if(id==null){
            return Result.error("请先登录！");
        }

        if(!id.equals("root")){
            user.setId(id);
            user.setPwd(null);
        }

        if(user.getName()==null||user.getAddress()==null){
            return Result.error("不能为空");
        }
        else if(user.getAddress().length()<1||user.getName().length()<1){
            return Result.error("不能为空");
        }

        if(user.getPwd()==null||user.getPwd().equals("")){
            user.setPwd(null);
        }

//        隐藏密码
        sellerService.updateById(user);
        user.setPwd("none");

        if(!id.equals("root")){//销售员修改自己
            makeTime(user.getId(), request, "修改销售账号");
        }
        else{//管理员修改销售员
            makeTime(user.getId(), request, "修改销售账号");
            makeTime("root", request, "修改销售账号:"+user.getId());
        }

        return Result.success(user);
    }

    //为顾客和管理员提供销售人员的分页
    @PostMapping("/page")
    public Result<Page<Seller>> page(@RequestBody Map<String, Integer> pageNum, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||(userId.charAt(0)!='u'&&!userId.equals("guest")&&!userId.equals("root"))){
            return Result.error("请登录");
        }

        if(pageNum.get("pageNum")==null){
            return Result.error("无效页码");
        }
        Page<Seller> pageInfo = new Page<>(pageNum.get("pageNum"), 10);
        LambdaQueryWrapper<Seller> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Seller::getId, "root");
        sellerService.page(pageInfo, queryWrapper);

//        隐藏密码
        for(int i=0;i<pageInfo.getRecords().size();i++){
            pageInfo.getRecords().get(i).setPwd("None");
        }

//        记录日志
        makeTime(userId, request, "查看销售员分页");

        return Result.success(pageInfo);
    }


    //管理员新增销售人员
    @PostMapping("/newSeller")
    public Result<String> newSeller(@RequestBody Seller seller, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||!userId.equals("root")){
            return Result.error("请管理员登录");
        }

        if(seller==null){
            return Result.error("请输入信息");
        }
        if(seller.getId()==null||seller.getPwd()==null||seller.getId().equals("")||seller.getPwd().equals("")){
            return Result.error("请输入id及密码");
        }

        seller.setId("s"+seller.getId());

        Seller seller1 = sellerService.getById(seller.getId());
        if(seller1!=null){
            return Result.error("id已存在");
        }

        sellerService.save(seller);

//        记录日志
        makeTime("root", request, "首次创建销售账号:"+seller.getId());
        makeTime(seller.getId(), request, "首次创建销售账号");
        return Result.success("添加成功");
    }

    //管理员移除销售人员
    @PostMapping("/remove")
    public Result<String> remove(@RequestBody Seller seller, HttpServletRequest request){
//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||!userId.equals("root")){
            return Result.error("请管理员登录");
        }

        if(seller==null){
            return Result.error("请输入信息");
        }

        sellerService.removeById(seller);

//        记录日志
        makeTime("root",request,"移除销售账号:"+seller.getId());

        return Result.success("已删除");
    }

    //管理员查看操作日志
    @PostMapping("/time")
    public Result<Page<Time>> time(@RequestBody Map<String, String> pageNum){

//        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||!userId.equals("root")){
            return Result.error("请管理员登录");
        }

        //传入的type= 0:查看用户操作，1:查看销售员操作，2:查看管理员操作

        Integer type = Integer.parseInt(pageNum.get("type"));

        LambdaQueryWrapper<Time> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.orderByDesc(Time::getTime);

//        pageNum中，user为筛选的id条件，operate为筛选的操作

        if(type==0){
            queryWrapper.likeRight(Time::getUserid, "u%");
            if(pageNum.get("user")!=null&&!pageNum.get("user").equals("")){
                queryWrapper.eq(Time::getUserid, "u"+pageNum.get("user"));
            }
            if(pageNum.get("operate")!=null&&!pageNum.get("operate").equals("")){
                if(pageNum.get("operate").equals("登录")){
                    queryWrapper.eq(Time::getType, 0);
                }
                else if(pageNum.get("operate").equals("登出")){
                    queryWrapper.eq(Time::getType, 1);
                }
                else{
                    queryWrapper.likeRight(Time::getOperate, pageNum.get("operate")+"%");
                }
            }
        }
        else if(type==1){
            queryWrapper.likeRight(Time::getUserid, "s%");
            if(pageNum.get("user")!=null&&!pageNum.get("user").equals("")){
                queryWrapper.eq(Time::getUserid, "s"+pageNum.get("user"));
            }
            if(pageNum.get("operate")!=null&&!pageNum.get("operate").equals("")){
                if(pageNum.get("operate").equals("登录")){
                    queryWrapper.eq(Time::getType, 2);
                }
                else if(pageNum.get("operate").equals("登出")){
                    queryWrapper.eq(Time::getType, 3);
                }
                else{
                    queryWrapper.likeRight(Time::getOperate, pageNum.get("operate")+"%");
                }
            }
        }
        else if(type==2){
            queryWrapper.eq(Time::getUserid, "root");
            if(pageNum.get("operate")!=null&&!pageNum.get("operate").equals("")){
                if(pageNum.get("operate").equals("登录")){
                    queryWrapper.eq(Time::getType, 5);
                }
                else if(pageNum.get("operate").equals("登出")){
                    queryWrapper.eq(Time::getType, 6);
                }
                else{
                    queryWrapper.likeRight(Time::getOperate, pageNum.get("operate")+"%");
                }
            }
        }

        if(pageNum.get("pageNum")==null){
            return Result.error("无效页码");
        }
        Page<Time> pageInfo = new Page<>(Integer.parseInt(pageNum.get("pageNum")), 10);
        timeService.page(pageInfo, queryWrapper);

        return Result.success(pageInfo);
    }

    //    用于管理员查询
    @PostMapping("/search")
    public Result<Seller> search(@RequestBody Seller seller){
        //        用户校验
        String userId = BaseContext.getCurrentId();
        if(userId==null||!userId.equals("root")){
            return Result.error("请管理员登录");
        }

        Seller seller1 = sellerService.getById(seller.getId());
        if(seller1==null){
            return Result.error("无");
        }
        seller1.setPwd("none");

        return Result.success(seller1);
    }
}
